package org.jash.mvp2206.news;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import org.jash.mvp2206.R;
import org.jash.mvp2206.entity.NewsPage;
import org.jash.mvp2206.mvp.BaseFragment;


public class NewsFragment extends BaseFragment<Construct.INewsView, NewsPresenter> implements Construct.INewsView {


    private static final String ARG_CATEGORY_ID = "CategoryId";


    private int categoryId;
    private int page = 1;
    private int size = 10;
    private RNewsAdapter adapter;
    private RecyclerView list;
    private SmartRefreshLayout refresh;
    public NewsFragment() {
        // Required empty public constructor
    }

    public static NewsFragment newInstance(int categoryId) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_CATEGORY_ID, categoryId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            categoryId = getArguments().getInt(ARG_CATEGORY_ID);
        }
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initData() {
        presenter = new NewsPresenter();
        presenter.getNewsPage(categoryId, page = 1, size);
    }

    @Override
    protected void initView() {
        list = getView().findViewById(R.id.list);
        refresh = getView().findViewById(R.id.refresh);
        adapter = new RNewsAdapter();
        adapter.setListener(bean -> startActivity(new Intent(requireContext(), DetailActivity.class).putExtra("id", bean.getId())));
        list.setAdapter(adapter);
        refresh.setOnRefreshListener(v -> presenter.getNewsPage(categoryId, page = 1, size));
        refresh.setOnLoadMoreListener(v -> presenter.getNewsPage(categoryId, ++page, size));

    }

    @Override
    public void newsPageSuccess(NewsPage.DataBean bean) {
        if (page == 1) {
            adapter.clear();
        }
        adapter.addAll(bean.getRecords());
        refresh.closeHeaderOrFooter();
    }

    @Override
    public void failure(Throwable t) {
        Toast.makeText(requireContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        refresh.closeHeaderOrFooter();
    }
}